package com.yue.mytomcat.ex01.webcontainer;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 功能描述: TODO <br/>
 * 创建时间: 2016/8/2<br/>
 *
 * @author QiuYang
 */
public class HttpServer {

    public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";

    private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
    private boolean shutdown = false;

    private void await() {
        ServerSocket serverSocket = null;
        int port = 8080;

        try {
            serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));   // 创建一个socket服务
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

        while(!shutdown){
            Socket socket = null;
            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                socket = serverSocket.accept();             // 接收浏览器请求， 创建客户端socket。
                inputStream = socket.getInputStream();
                outputStream = socket.getOutputStream();

                Request request = new Request(inputStream); // 根据客户端socket的inputStream 创建Request对象
                request.parse();                            // 解析request对象

                Response response = new Response(outputStream); // 根据客户端socket的OutputStream 创建response对象
                response.setRequest(request);
                response.sendStaticResource();                  // 向浏览器发送请求资源

                socket.close();
                shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }





    public static void main(String[] args) {
//        System.out.println(System.getProperty("user.dir"));
//        System.out.println(File.separator);
        HttpServer server = new HttpServer();
        server.await();
    }

}
